package com.endpoint.member.controller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.endpoint.common.utils.JwtTokenUtil;
import com.endpoint.common.utils.ResultBean;
import com.endpoint.common.valid.AddGroup;
import com.endpoint.member.dto.MemberDto;
import com.endpoint.member.entity.Member;
import com.endpoint.member.service.MemberService;
import com.endpoint.member.to.MemberTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Jack_Li
 * @since 2024-07-03
 */
@Slf4j
@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private MemberService memberService;

    @PostMapping("/save")
    public ResultBean save(@Validated({AddGroup.class}) @RequestBody MemberDto member){
        Member data = new Member();
        data.setUsername(member.getUsername());
        data.setPassword(member.getPassword());

        memberService.save(data);
        return ResultBean.ok();
    }

    @PostMapping("/queryByIds")
    public List<MemberTo> queryByIds(@RequestBody List<Long> ids){
        List<Member> members = memberService.list(Wrappers.<Member>lambdaQuery()
                .in(Member::getId,ids)
        );
        Vector<MemberTo> tos = new Vector<>();
        members.forEach(member -> {
            MemberTo to = new MemberTo();
            BeanUtils.copyProperties(member,to);
            tos.add(to);
        });
        return tos;
    }

    @GetMapping("/getAccountBalance")
    public ResultBean<Map> getAccountBalance(@RequestHeader("Authorization") String token){
        Long userId = JwtTokenUtil.getUserIdFromToken(token);
        Member member = memberService.getById(userId);
        Map<String,Object> map = new HashMap<>();
        map.put("accountBalance", member.getAccountBalance());
        return ResultBean.ok(map);
    }

    @PostMapping("/addAmount")
    public ResultBean addAmount(@RequestParam("userId") Long userId,@RequestParam("totalAmount") Integer totalAmount){
        log.warn("userId:{},totalAmount:{}", userId, totalAmount);
        Member member = memberService.getById(userId);
        member.setAccountBalance(member.getAccountBalance()+totalAmount);
        memberService.updateById(member);
        return ResultBean.ok();
    }



}

